package rpg.client.player.swing;

import java.util.List;

import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import rpg.client.GameEngine;
import rpg.client.model.Actor;
import rpg.client.model.GameEvent;
import rpg.client.player.swing.create.CreateCharacterJPanel;

class CreateAndStartGui implements Runnable {
	private final GameEngine engine;

	CreateAndStartGui(final GameEngine ge) {
		super();
		engine = ge;
	}

	@Override
	public void run() {
		final PlayerJDialog pjd = new PlayerJDialog(engine);
		pjd.setVisible(true);
	}
}

public class PlayerJDialog extends JDialog implements TopContainer {
	public static void launch(final GameEngine engine) {
		final Runnable runnable = new CreateAndStartGui(engine);
		SwingUtilities.invokeLater(runnable);
	}

	private final GameEngine gameEngine;
	private final CreateCharacterJPanel createCharacter = new CreateCharacterJPanel(
			this);
	private final GameJPanel game;

	PlayerJDialog(final GameEngine ge) {
		super();
		gameEngine = ge;
		game = new GameJPanel(this, ge);
		initGui();
	}

	@Override
	public void awtSubmitPlayer(final Actor.Builder playerBuilder) {
		final Actor player = gameEngine.registerPlayer(playerBuilder);
		game.setPlayerID(player.getId());
		final List<GameEvent> events = gameEngine.addPlayer(player);
		game.render(events);
		moveToTop(game);
	}

	private void initGui() {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		moveToTop(createCharacter);
	}

	private void moveToTop(final JPanel panel) {
		getContentPane().removeAll();
		getContentPane().add(panel);
		pack();
		panel.requestFocus();
	}

	@Override
	public void repack() {
		pack();
	}
}
